<?php

class ArticleTable extends Doctrine_Table
{
  public function getBackendListQuery(Doctrine_Query $query)
  {
    $rootAlias = $query->getRootAlias();

		$user = sfContext::getInstance()->getUser();

		if ($user->hasCredential('editor'))
		{
			$query->addWhere(
				"$rootAlias.publisher_id = ?", 
				$user->getAttribute('id')
		  );
		} 
    else
    {
      $query->innerJoin("$rootAlias.publisher p")
				->innerJoin("$rootAlias.area a");
        
      if ($user->hasCredential('admin'))
      {            
        $query->andWhereIn("$rootAlias.area_id", $user->getAreaIds());
      }
    }

		return $query;
  }
  
  public function getAvailableQuery()
  {
    return $this->createQuery('a')
      ->orderBy('a.id desc');
  }
  
  public function getWithCategoryQuery()
  {
    return $this->createQuery('a')
      ->innerJoin('a.categories c')
      ->orderBy('id desc');
  }
  
  public function getByCategoryQuery($category)
  {
    return $this->getWithCategoryQuery()
      ->addWhere('c.category = ?', $category);
  }
}
